<?php

class QueryRESTController extends DooController {

 	public function beforeRun($resource, $action)
    {
        //Init
        $this->res = new response();

        //set content type
        $this->contentType = 'json';
    }

    public function afterRun($routeResult)
    { 
    	//Display Results
        if (isset($this->contentType))
            $this->setContentType($this->contentType);
        
        echo $this->res->to_json();
    }

	//POST
	function submit(){	
		require_once 'shard-query.php'; 
	
		//Check required Fields
		$missing = false;	
		if(!isset($_POST["sql"]) || strlen($_POST["sql"]) == 0)
			$missing = true;
		
		if($missing){
			$this->res->success = false;
			$this->res->message = "missing required field!";
			return null;
		}
		
		//get vars
		$sql = $_POST["sql"];
		$schema_id = $this->params['schema_id'];
		$schema = Doo::db()->getOne('Schemata', array('where' => 'id = ' . $schema_id));		

		//init
		$shard_query = new ShardQuery($schema->schema_name);
		$shard_query->verbose = true;
				
		//execute query
		$stmt = $shard_query->query($sql);

		//check results
		if(!$stmt || $shard_query->error) {
			//return
			$this->res->data = $shard_query->error;
			$this->res->success = false;
			return null;
		}
		
		//build data
		$this->res->data = $this->json_format($shard_query, $stmt);
		$this->res->message = $shard_query->messages;
	
		//return
		$this->res->success = true;
	}
 
	private function json_format($shard_query, $stmt){
		$data = array();
		//loop rows
		while($row = $shard_query->DAL->my_fetch_assoc($stmt)) {
			$data[] = $row;
		}
		return $data;
	}

}
?>
